package xing.test.voice.rtp.redfire;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioFileFormat;
import java.io.File;
import java.io.FileOutputStream;

/**
 * AudioReceiver is a pure-java audio stream receiver. It uses the javax.sound
 * library (package).
 */
public class AudioReceiverXing {

	// ******************************* MAIN *******************************

	/** The main method. */
	public static void main(String[] args) {
		int port = 10000;

		int sample_rate = 8000;
		int sample_size = 1;
		boolean linear_signed = false;
		boolean pcmu = false;
		boolean big_endian = false;
		String filename = null;
		boolean sound = true;

		boolean help = true;

		if (help) {
			System.out
					.println("usage:\n  java AudioReceiver <local_port> [options]");
			System.out.println("   options:");
			System.out.println("   -h               this help");
			System.out.println("   -F <audio_file>  records to audio file");
			System.out
					.println("   -S <rate> <size> sample rate [B/s], and size [B]");
			System.out
					.println("   -Z               uses PCM linear signed format (linear unsigned is used as default)");
			System.out.println("   -U               uses PCMU format");
			System.out.println("   -E               uses big endian format");
		}

		try {
			RtpStreamReceiver receiver = null;
			AudioOutput audio_output = null;
			if (sound)
				AudioOutput.initAudioLine();

			if (sound) {
				// AudioFormat format = new AudioFormat(codec, sample_rate,
				// 8 * sample_size, 1, sample_size, sample_rate,
				// big_endian);
				// AudioFormat format = new AudioFormat(8000, 8, 1, true, true);
				AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_UNSIGNED;
				int rate = 8000;
				int sampleSize = 8;
				boolean bigEndian = true;
				int channels = 1;
				AudioFormat format = new AudioFormat(encoding, rate,
						sampleSize, channels, (sampleSize / 8) * channels,
						rate, bigEndian);
				System.out.println("System audio format: " + format);
				audio_output = new AudioOutput(format);
				receiver = new RtpStreamReceiver(audio_output.getOuputStream(),
						port);
			}

			receiver.start();
			if (sound)
				audio_output.play();

			System.out.println("Press 'Return' to stop");
			System.in.read();

			receiver.halt();
			if (sound)
				audio_output.stop();
			if (sound)
				AudioOutput.closeAudioLine();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
